package com.example.demo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.example.demo.model.Order;
import com.example.demo.model.OrderStatus;
import com.example.demo.model.PaymentRecord;
import com.example.demo.model.PaymentStatus;
import com.example.demo.model.Result;
import com.example.demo.param.PaymentParam;
import com.example.demo.param.PaymentRecordQueryParam;
import com.example.demo.service.OrderService;
import com.example.demo.service.PayService;
import com.example.demo.service.PaymentRecordService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PayServiceImpl implements PayService {

    @Autowired
    private OrderService orderService;
    @Autowired
    private PaymentRecordService paymentRecordService;

    //ObjectMapper 主要用于在 Java 对象和 JSON 数据之间进行相互转换，也就是序列化和反序列化操作。
    private ObjectMapper objectMapper = new ObjectMapper();

    @Value("${alipay.app.id:2021001172660270}")
    private String aliPayAppId;//支付宝应用id

    @Value("${alipay.app.privatekey:MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCnv9kfis56VG2XVZxAq5S10aEumZgV3VvoOD5VdpMrd9wfRuRRI7fMsDB0HXo5uHkJZ+SXzaJh1CQl5R6HrSX64EZy9/5sHyFRKabPY4Nxrrzi++tS4C/SFYYT6TYEKAzMk7wWBP0NvFhbNfVpne8dE6K98NYLkz5kAXXHHQWyPQqxTDN/Iq6+0ZJa6o+7JXYO3CEC8+qEvYCo478G9PA0ooWvEVargdHPavXBwHH0TfXyxwS3prG2LUmhf+a9qUxbtN1BKsujtm+ff//S5RY1TDwwhR0GnLUG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uepNan/bqjhhUZ1f8Cipd3XXNSrjBAoGAQ2pc7xh1jxCTTtN+EmxQRGjwid0AcDEZAn4m00mCFkRhvVfa4Df5GcAgNajTBsttdi/DXtu216whQ7ceYKAPsKzEO4w7R7DoMzhnL9NqNtL9uogwwYO72uPEVn4c+hQS/qFRmSsfIkCrT2J5sGuXU7+4gUO8V8Ox+RIOt6kkG6Y=}")
    private String aliPayAppPrivateKey;//应用公钥

    @Value("${alipay.publickey:MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkJAtCWlSvkZ05srfAmvOt/XU701GmpF3aO7XozmmZbzjTOUAcc8BzrAsqIeXJVOPRJz75fCVZ6rcsx4P2PWGHCoB293RPJpBnDT1VBVMq7k8Hw9VOJRuq56L0PZxtVHYjUA8i4vUmXc8j5K4rLGp+PC9VqNVJpj8Njv2R3ZeLndAd0B1//73SfKRSRZMNoPAl/XPSY7MAfGLzNm3B3FPVbJIEt9TM+/ijtlLpzTFCDLaLvy8EFsvoZwgpVkbxT9iRFvFWomz29/oH4xkSsZFaTMeswPUyERoMXhqMmW8hmVT/yBjiEx/NNC32Bu0Ic4DD01JZXDr/jDDjh1IA2uYNQIDAQAB}")
    private String aliPayPublicKey;//支付宝公钥

    @Autowired
    private KafkaTemplate kafkaTemplate;

    public Result aliPay(String orderId, PaymentParam paymentParam) {
        Result result = new Result();
        //实例化客户端
        //第一个参数是支付宝网关地址，
        // 第二个参数是 APPID，在生成应用时会提供，
        // 第三个参数表示应用公钥，
        // 第四个参数表示格式是 JSON 格式，
        // 第五个参数表名编码格式是 UTF-8，
        // 第六个参数是支付宝公钥，
        // 第七个表示签名方式为RSA2
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliPayAppId,aliPayAppPrivateKey, "json", "UTF-8", aliPayPublicKey, "RSA2");
        //创建API对应的request
        AlipayTradeWapPayRequest request = getAlipayTradeWapPayRequest(orderId, paymentParam);

        AlipayTradeWapPayResponse response = null;
        try {
            //调用SDK生成表单
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
           e.printStackTrace();
        }
        if (response.isSuccess()) {
            System.out.println("支付成功");
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 组装支付宝支付参数
     *
     * @param orderId      订单号
     * @param paymentParam 支付参数
     * @return AlipayTradeWapPayRequest
     */
    private AlipayTradeWapPayRequest getAlipayTradeWapPayRequest(String orderId, PaymentParam paymentParam) {
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        //api版本号
        request.setApiVersion("1.0");
        //返回的url
        request.setReturnUrl("");
        //通知的url
        request.setNotifyUrl("");
        Map<String, Object> bizContentMap = new HashMap<>();
        //订单号
        bizContentMap.put("out_trade_no", orderId);
        //总金额
        bizContentMap.put("total_amount", paymentParam.getPayAmount());
        //退出的url
        bizContentMap.put("quit_url", "");
        //产品码
        bizContentMap.put("product_code", "QUICK_WAP_WAY");
        try {
            request.setBizContent(objectMapper.writeValueAsString(bizContentMap));
        } catch (JsonProcessingException e) {
           e.printStackTrace();
        }
        return request;
    }

    @Override
    public Result payOrder(PaymentParam paymentParam) {
        Result result = new Result<>();
        //1.创建支付流水记录
        PaymentRecord paymentRecord = new PaymentRecord();
        paymentRecord.setPayType(paymentParam.getPayType());
        paymentRecord.setPayStatus(PaymentStatus.PENDING);//支付状态 支付中
        paymentRecord.setUserId(paymentParam.getUserId());
        paymentRecord.setOrderNumber(paymentParam.getOrderNumber());
        paymentRecord.setAmount(paymentParam.getPayAmount());
        paymentRecordService.save(paymentRecord);
        //2.支付操作
        switch (paymentParam.getPayType()) {
            case ALIPAY:
                result = aliPay(paymentParam.getOrderNumber(), paymentParam);
                break;
            default:
                break;
        }
        return result;
    }

    @Override
    public Result alipaycallback(Map<String, String> map) {
        Result result = new Result();
        String status = map.get("trade_status");//订单状态
        String orderNum = map.get("out_trade_no");//订单号
        String endTime = map.get("gmt_close");//支付完成时间

        Order order = orderService.getByOrderNumber(orderNum);
        PaymentRecord paymentRecord = null;
        PaymentRecordQueryParam queryParam = new PaymentRecordQueryParam();
        queryParam.setOrderNumber(orderNum);
        List<PaymentRecord> paymentRecords = paymentRecordService.query(queryParam);
        if (CollectionUtils.isEmpty(paymentRecords)) {
            result.setMessage("支付流水不存在");
        }else {
            paymentRecord = paymentRecords.get(0);
        }
        if (order != null) {
            if ("TRADE_SUCCESS".equals(status)) {//交易成功
                result.setMessage("交易成功");
                //1.更新订单状态
                orderService.updateStatus(orderNum,OrderStatus.TRADE_PAID_SUCCESS);
                //2.更新支付流水
                if (paymentRecord!=null) {
                    paymentRecord.setPayStatus(PaymentStatus.SUCCESS);
                    paymentRecordService.update(paymentRecord); //更新支付流水状态
                }
                //3.更新商品付款人数
                orderService.updateProductPersonNumber(orderNum);
                //4.发送消息
                kafkaTemplate.send("dewuPayment", JSON.toJSONString(paymentRecord));
            }else if ("TRADE_CLOSED".equals(status)) { //交易关闭
                result.setMessage("交易关闭");
                orderService.updateStatus(orderNum, OrderStatus.TRADE_PAID_FAILED);
                if (paymentRecord!=null) {
                    paymentRecord.setPayStatus(PaymentStatus.FAILURE);
                    paymentRecordService.update(paymentRecord); //更新支付流水状态
                }
            }
            result.setSuccess(true);
        }else {
            result.setMessage("订单不存在");
        }
        return result;
    }
}